package com.yy.qpgame.server.util;

public class CodeUtils {
    /**
     * 加密
     *
     * @param source 未加密的字符串
     * @param passWord 密码
     * @return
     */
    public static byte[] encode(byte[] source, String passWord) {
        byte[] passWordArr = passWord.getBytes();
        //先进行异或运算
        //在此前后进行其他个性化算法
        byte[] bytes = xorByteArray(source, passWordArr);
        return bytes;
    }

    /**
     * 解密
     *
     * @param encodeStr 已经加密过的字符串
     * @param passWord 密码
     * @return
     */
    public static byte[] decode(byte[] encodeSouce, String passWord) {
        byte[] passWordArr = passWord.getBytes();
        //再进行异或运算
        byte[] bytes = xorByteArray(encodeSouce, passWordArr);
        //在此前后进行其他个性化算法
        return bytes;
    }

    /**
     * 对两个字节数组进行抑或运算
     *
     * @param arr1 基本数组
     * @param arr2 运算数组
     * @return
     */
    public static byte[] xorByteArray(byte[] arr1, byte[] arr2) {
        int len2 = arr2.length;
        byte[] arr3 = new byte[arr1.length];
        for (int i = 0; i < arr1.length; i++) {
            arr3[i] =  (byte) (arr1[i] ^ arr2[i % len2]);
        }
        return arr3;
    }
    
    public static String bytes2HexString(byte[] b) {
    	String ret = "";
    	for (int i = 0; i < b.length; i++) {
    		String hex = Integer.toHexString(b[i] & 0xFF);
    		if (hex.length() == 1) {
    			hex = '0' + hex;
    		}
    		ret += hex;
    	}
    	return ret;
    }
    
    public static byte[] intToByteArray(int a) {   
    	return new byte[] {   
    			(byte) ((a >> 24) & 0xFF),   
    			(byte) ((a >> 16) & 0xFF),      
    			(byte) ((a >> 8) & 0xFF),      
    			(byte) (a & 0xFF)   
    	};   
    } 
    
  //将整数按照小端存放，低字节出访低位
    public static byte[] toLH(int n) {
        byte[] b = new byte[4];
        b[0] = (byte) (n & 0xff);
        b[1] = (byte) (n >> 8 & 0xff);
        b[2] = (byte) (n >> 16 & 0xff);
        b[3] = (byte) (n >> 24 & 0xff);
        return b;
    }
    
}